/*
 * @Description: 最小订单金额规则页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2020-10-21 17:30:52
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-25 16:59:29
 */
import React, { useMemo, useRef } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import { Button, DataSet, Modal, notification, Select, Table } from 'choerodon-ui/pro';
import { ButtonColor, FuncType } from 'choerodon-ui/pro/lib/button/enum';
import { useDataSet } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import { ColumnLock, TableColumnTooltip } from 'choerodon-ui/pro/lib/table/enum';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import intl from 'utils/intl';

import { minOrderListDataSet } from '../../stores/minOrderListDS';
import { renderSort, addEnterCallBack } from '../../utils/utilsFun';
import CustomizeTableSearch from '@common/components/CustomizeTableSearch';
import AreaTree from './component/areaTree';
import querystring from 'querystring';
import { areaDateSet } from '../../stores/minOrderDtlDS';
import formatterCollections from 'utils/intl/formatterCollections';

notification.config({
  duration: 3,
  placement: 'bottomRight',
});
interface propstype {
  dispatch: any;
}

const ClassPage: React.FC<propstype> = ({ dispatch }) => {
  const tableDS = useDataSet(() => new DataSet(minOrderListDataSet() as DataSetProps));
  const areaDS = useDataSet(() => new DataSet(areaDateSet() as DataSetProps));

  const pageRef = useRef(null);
  const ref = useRef(null as any)
  // 添加按回车查询事件
  addEnterCallBack(tableDS, pageRef);

  const handleToDetail = record => {
    const id = record.get('ruleId');
    dispatch(
      routerRedux.push({
        pathname: `/o2om/min-order-amount-rule/create`,
        search: querystring.stringify({
          params: encodeURIComponent(JSON.stringify({ id, edit: true })),
        }),
      })
    );
  };

  const handleCreate = () => {
    dispatch(
      routerRedux.push({
        pathname: `/o2om/min-order-amount-rule/create`,
      })
    );
  };

  const handleLook = record => {
    const ruleId = record.get('ruleId');
    const regionId = record.get('regionId');
    setTimeout(() => {
      areaDS.setQueryParameter('largeAreaId', regionId);
      areaDS.query().then(() => {        
        ref.current?.renderSelectedTreeFn()
      });
    },10)
    Modal.open({
      key: 'detailModalKey',
      title: intl.get(`dji.otc.om.view.title.applicableRegion`).d('适用区域国家'),
      closable: true,
      drawer: false,
      children: (
        <div>
          <AreaTree areaDS={areaDS} ruleId={ruleId} parentDS={tableDS} refFN={ref} disabledFlag={true}/>
        </div>
      ),
      onCancel: () => areaDS.reset(),
      onOk: () => areaDS.reset(),
    });
  };

  const Columns = useMemo<any>(
    () => [
      {
        header: intl.get(`dji.otc.om.view.field.serialNumber`).d('序号'),
        width: 50,
        lock: true,
        renderer: ({ record }) => renderSort(record, tableDS),
      },
      {
        name: 'businessGroup',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        lock: true,
        width: 100,
      },
      { name: 'largeAreaName', align: 'left', tooltip: TableColumnTooltip.always },
      {
        name: 'areaControy',
        align: 'center',
        maxWidth: 120,
        renderer: ({ record }) => {
          return (
            <Button
              funcType={'flat' as FuncType}
              key="look"
              onClick={() => {
                handleLook(record);
              }}
            >
              <a key="look">{intl.get(`dji.otc.om.view.button.look`).d('查看')}</a>
            </Button>
          );
        },
      },
      { name: 'amountRuleType', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'priority', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'createdBy', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'creationDate', align: 'left', tooltip: TableColumnTooltip.always },
      {
        header: intl.get('dji.otc.om.view.field.operationColumn').d('操作'),
        width: 150,
        lock: ColumnLock.right,
        command: ({ record }) => {
          return [
            <Button
              funcType={'flat' as FuncType}
              key="look"
              onClick={() => {
                handleToDetail(record);
              }}
            >
              <a key="look">{intl.get(`dji.otc.om.view.button.edit`).d('编辑')}</a>
            </Button>,
            <Button
              funcType={'flat' as FuncType}
              key="delete"
              onClick={() => {
                tableDS.delete(record);
              }}
            >
              <a key="delete">{intl.get(`dji.otc.om.view.button.delete`).d('删除')}</a>
            </Button>,
          ];
        },
      },
    ],
    []
  );

  const handleDelete = () => {
    const seletedRecord = tableDS.selected;
    if (seletedRecord.length === 0) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.reminder.selectDeleteData`).d('请勾选删除的数据'),
      });
      return;
    }
    tableDS.delete(seletedRecord);
  };

  return (
    <div ref={pageRef}>
      <PageHeaderWrapper
        title={intl.get('dji.otc.om.view.menu.minOrderAmountRule').d('最小订单金额规则')}
        header={
          <div>
            <Button onClick={() => handleCreate()} color={ButtonColor.primary} key="create">
              {intl.get(`dji.otc.om.view.button.create`).d('新建')}
            </Button>
            <Button onClick={() => handleDelete()} key="delete">
              {intl.get(`dji.otc.om.view.button.delete`).d('删除')}
            </Button>
          </div>
        }
      >
        <Table
          dataSet={tableDS}
          border
          queryFieldsLimit={3}
          columns={Columns}
          queryBar={props => (
            <CustomizeTableSearch
              elements={[
                <Select name="businessGroup" key="businessGroup" searchable />,
                <Select name="regionId" key="regionId" searchable />,
              ]}
              {...props}
            />
          )}
        />
      </PageHeaderWrapper>
    </div>
  );
};

export default connect()(
  formatterCollections({
    code: 'dji.otc.om',
  })(ClassPage)
);